<?php

class TBB_Validate_UniqueUsername extends Zend_Validate_Abstract {
	
    const USERNAME_EXISTS = 'usernameExists';

    protected $_messageTemplates = array(
        self::USERNAME_EXISTS => 'Người dùng "%value%" đã tồn tại',
    );

    public function __construct(TBB_Model_Users $userModel)
    {
        $this->_userModel = $userModel;
    }

    public function isValid($value, $context = null)
    {   	
    	$value = ( string ) $value;
		$this->_setValue ( $value );		
		
		// editting user
		if(isset($context['user_id']) && $context['user_id'] != '') {
			return true;
		}
		// other cases
    	$exists = $this->_userModel->userExists($value);	
		if($exists) {	    		
	    	$this->_error(self::USERNAME_EXISTS);	    		
	    	return false;
	    }
	    return true;
    }
}

